const routing = require('@/routes/index')
const koaBody = require('koa-body')
const koaStatic = require('koa-static')
const error = require('koa-json-error')
const parameter = require('koa-parameter')
const path = require('path')
const R = require('@/controller/common/baseController')
const { publicPath, routes } = require('./whiteList')

module.exports = (app) => {
    app.use(koaStatic(path.join(__dirname, '/public')))

    app.use(error({
        // postFormat: (e: any, {stack, ...rest}:any) => process.env.NODE_ENV === 'production' ? R.fail(rest) : R.fail({stack, ...rest})
        postFormat: (e, {stack, ...rest}) =>  R.fail(rest)
    }))

    app.use(koaBody({
        multipart: true,
        formidable: {
            uploadDir: path.join(__dirname, '../public/uploads'),
            keepExtensions: true
        }
    }))
    app.use(parameter(app))

    app.use(async (ctx, next) => {
        if (routes.includes(ctx.url.replace(publicPath, ''))){
            await next()
            return
        }
        await R.auth(ctx, next)
    })
    routing(app)
}